package com.njcb.ams.service.workflow;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.njcb.ams.util.AmsUtils;
import com.njcb.ams.util.WrokflowServiceUtils;

/**
 * 流程定义部署服务
 * 
 * @author liuyanlong
 *
 */
@Service
public class WrokflowDefinitionService {

	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private TaskService taskService;

	/**
	 * 发布流程
	 * 
	 * @param processname
	 */
	public void processDeploy(String processname) {
		this.repositoryService.createDeployment().addClasspathResource("resources/workflow/" + processname + ".bpmn").deploy();
	}

	/**
	 * 根据任务ID查询流程定义key
	 * 方法功能描述：
	 * 
	 * @param taskId
	 * @return
	 */
	public String getTaskDefinitionKey(String taskId) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		String processDefinitionKey = task.getTaskDefinitionKey();
		return processDefinitionKey;
	}
	
	/**
	 * 
	 * 方法功能描述：流程定义查询
	 * 
	 * @param inBean
	 * @return
	 */
	public List<ProcessDefinition> queryProcessDefinition(ProcessDefinition inBean) {
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		if(AmsUtils.isNotNull(inBean.getName())){
			query.processDefinitionNameLike(inBean.getName());
		}
		if(AmsUtils.isNotNull(inBean.getKey())){
			query.processDefinitionKeyLike(inBean.getKey());
		}
		query.orderByProcessDefinitionVersion().asc();
		return WrokflowServiceUtils.pageQuery(query);
	}
	
	
	/**
	 * 
	 * 方法功能描述：流程定义删除
	 * 
	 * @param inBean
	 * @return
	 */
	public void deleteProcessDefinition(ProcessDefinition inBean) {
		repositoryService.deleteDeployment(inBean.getDeploymentId());
	}
	

	/**
	 * 根据任务ID查询流程实例ID
	 * 方法功能描述：
	 * 
	 * @param taskId
	 * @return
	 */
	public String getProcessInstanceId(String taskId) {
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		String processInstanceId = task.getProcessInstanceId();
		return processInstanceId;
	}

	/**
	 * 查询最新的流程定义
	 */
	public List<ProcessDefinition> findLastVersionProcessDefinition() {
		List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().list();

		Map<String, ProcessDefinition> map = new LinkedHashMap<>();
		if (null != list && list.size() > 0) {
			for (ProcessDefinition pd : list) {
				map.put(pd.getKey(), pd);
			}
		}

		List<ProcessDefinition> processDefinitions = new ArrayList<>(map.values());
		return processDefinitions;
	}

}
